#include "esp_lvgl_port.h"
#include "esp_log.h"
#include "logic_analyzer_ui.h"
#include "logic_analyzer_sump.h"
#include "main_ui.h"
#include "md_images.h"
#include "func_pin_image.h"
#include "md_languages.h"
#include "work_status_setting.h"
#include "lcd.h"
// 声明字体
LV_FONT_DECLARE(myFont);
LV_FONT_DECLARE(lv_font_montserrat_14);
#define EABLE_LOGIC 1
void exit_logic_analyzer_ui(lv_obj_t *root)
{
   // bsp_lcd_init();
    switch_to_main_screen(); // 切换到主界面
    // refresh_main_screen();
    /*删除对应的逻辑分析仪界面，防止多次调用，内存泄漏*/
#if EABLE_LOGIC
    logic_analyzer_denit();        // 退出逻辑分析仪
    set_work_status(USUALLY_WORK); // Initialize NVS.
    //ESP_LOGI("debug", "exit logic analyzer ui");
#endif //EABLE_LOGIC
    /*因为功能界面多,而且不常用,所以删除*/
    lv_obj_del(root); //也可以把lv_scr_load_anim的auto_del设置为true

    // refresh_main_screen();
}

    // 手势事件回调
static void event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_GESTURE) {
        lv_indev_t *indev = lv_indev_get_act();
        if (!indev)
            return;

        lv_dir_t dir = lv_indev_get_gesture_dir(indev);

        // 保留右划检测
        if (dir == LV_DIR_RIGHT || dir == LV_DIR_TOP) {
            exit_logic_analyzer_ui(e->target);
        }
    }
}

// 全局指针声明
lv_obj_t *logic_dev_status_led = NULL;
lv_obj_t *logic_dev_status_label = NULL;
/* 
 * @ brief:创建逻辑分析仪界面
*/
lv_obj_t *create_logic_analyzer_ui()
{
    // 创建根容器（全屏黑色背景）
    lv_obj_t *root = lv_obj_create(NULL);
    if (!root)
        return NULL;
    lv_obj_set_size(root, lv_pct(100), lv_pct(100));
    lv_obj_set_style_bg_color(root, lv_color_black(), LV_PART_MAIN);
    lv_obj_add_event_cb(root, event_handler, LV_EVENT_GESTURE, NULL);

    // 创建主布局容器（垂直排列）
    lv_obj_t *main_container = lv_obj_create(root);
    if (!main_container)
        return root;
    lv_obj_remove_style_all(main_container);
    lv_obj_set_size(main_container, lv_pct(100), lv_pct(100));
    lv_obj_set_flex_flow(main_container, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_style_pad_all(main_container, 5, LV_PART_MAIN);//

    /******************** 顶部区域 ********************/
    lv_obj_t *top_container = lv_obj_create(main_container);
    if (!top_container)
        return root;
    lv_obj_remove_style_all(top_container);
    lv_obj_set_size(top_container, lv_pct(100), lv_pct(45));
    lv_obj_set_flex_flow(top_container, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(top_container,
                          LV_FLEX_ALIGN_SPACE_EVENLY,
                          LV_FLEX_ALIGN_CENTER,
                          LV_FLEX_ALIGN_CENTER);

    // 左侧徽标容器
    lv_obj_t *logo_container = lv_obj_create(top_container);
    if (!logo_container)
        return root;
    lv_obj_remove_style_all(logo_container);
    lv_obj_set_size(logo_container, LV_SIZE_CONTENT, lv_pct(90));
    lv_obj_set_flex_align(logo_container,
                          LV_FLEX_ALIGN_CENTER,
                          LV_FLEX_ALIGN_CENTER,
                          LV_FLEX_ALIGN_CENTER);

    const void *img_src = get_func_image_data(FUNC_LOGIC_ANALYZER, LOGIC_ANALYZER_NUM);
    if (img_src) {
        lv_obj_t *logo_img = lv_img_create(logo_container);
        if (logo_img) {
            lv_img_set_src(logo_img, img_src);
            lv_obj_center(logo_img);
        }
    }

    // 右侧信息面板
    lv_obj_t *info_panel = lv_obj_create(top_container);
    if (!info_panel)
        return root;
    lv_obj_remove_style_all(info_panel);
    lv_obj_set_size(info_panel, lv_pct(60), lv_pct(90));
    lv_obj_set_style_bg_color(info_panel, lv_color_hex(0x212121), LV_PART_MAIN);
    lv_obj_set_style_radius(info_panel, 12, LV_PART_MAIN);
    lv_obj_set_style_pad_all(info_panel, 15, LV_PART_MAIN);
    lv_obj_set_flex_flow(info_panel, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(info_panel,
                          LV_FLEX_ALIGN_SPACE_BETWEEN,
                          LV_FLEX_ALIGN_START,
                          LV_FLEX_ALIGN_CENTER);

    /******************** 设备信息 ********************/
    lv_obj_t *info_label = lv_label_create(info_panel);
    if (info_label) {
        lv_obj_set_style_text_font(info_label, &lv_font_montserrat_14, LV_PART_MAIN);
        lv_label_set_text(info_label, "Device: MdLink\n"
                                      "Channels: 8\n"
                                      "Sample Rate: 20MHz\n"
                                      "Buffer: 16Mpts");
        lv_obj_set_style_text_color(info_label, lv_color_white(), LV_PART_MAIN);
        lv_obj_set_style_text_line_space(info_label, 8, LV_PART_MAIN);
        lv_obj_set_style_pad_top(info_label, 5, LV_PART_MAIN); // 添加底部内边距
    }

    /******************** 底部区域 ********************/
    /******************** 底部区域 - 优化高度分配 ********************/
    lv_obj_t *bottom_container = lv_obj_create(main_container);
    if (!bottom_container)
        return root;
    lv_obj_remove_style_all(bottom_container);
    lv_obj_set_size(bottom_container, lv_pct(100), lv_pct(55));
    //lv_obj_set_style_pad_ver(bottom_container, 5, LV_PART_MAIN); // 减少垂直内边距
    lv_obj_set_flex_flow(bottom_container, LV_FLEX_FLOW_COLUMN);
    lv_obj_clear_flag(bottom_container, LV_OBJ_FLAG_SCROLLABLE);
    // 禁止bottom_container的默认滚动行为（如果有）
    lv_obj_set_scrollbar_mode(bottom_container, LV_SCROLLBAR_MODE_OFF);// 禁止滚动条
    lv_obj_set_scroll_dir(bottom_container, LV_DIR_NONE);              // 完全禁用滚动

    lv_obj_clear_flag(bottom_container, LV_OBJ_FLAG_SCROLLABLE); // 禁止默认滚动

    lv_obj_add_flag(bottom_container, LV_OBJ_FLAG_EVENT_BUBBLE); // 允许事件冒泡
    /******************** 状态栏 ********************/
    lv_obj_t *status_bar = lv_obj_create(bottom_container);
    if (!status_bar)
        return root;
    lv_obj_remove_style_all(status_bar);
    lv_obj_set_size(status_bar, lv_pct(100), 30);
    lv_obj_set_flex_flow(status_bar, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(status_bar,
                          LV_FLEX_ALIGN_SPACE_BETWEEN,
                          LV_FLEX_ALIGN_CENTER,
                          LV_FLEX_ALIGN_CENTER);
    lv_obj_set_style_pad_bottom(status_bar, 10, LV_PART_MAIN); // 减少底部留白

    // 标题
    lv_obj_t *title = lv_label_create(status_bar);
    if (title) {
        lv_label_set_text(title, get_func_txt_data(FUNC_LOGIC_ANALYZER, LOGIC_ANALYZER_NUM));
        lv_obj_set_style_text_color(title, lv_color_hex(0x6200EE), LV_PART_MAIN);
        lv_obj_set_style_text_font(title, &myFont, LV_PART_MAIN);
        lv_obj_set_style_text_align(title, LV_TEXT_ALIGN_CENTER, LV_PART_MAIN);
    }

    // 连接状态指示器 - 使用LED替代文本中的圆点
    lv_obj_t *status_container = lv_obj_create(status_bar);
    if (!status_container)
        return root;
    lv_obj_remove_style_all(status_container);
    lv_obj_set_size(status_container, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
    lv_obj_set_flex_flow(status_container, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(status_container,
                          LV_FLEX_ALIGN_CENTER,
                          LV_FLEX_ALIGN_CENTER,
                          LV_FLEX_ALIGN_CENTER);

    // LED状态指示灯
    lv_obj_t *status_led = lv_led_create(status_container);
    if (status_led) {
        lv_led_set_color(status_led, lv_color_hex(0xFF5555)); // 初始红色
        lv_led_off(status_led);
        lv_obj_set_size(status_led, 15, 15);
        lv_obj_set_style_radius(status_led, LV_RADIUS_CIRCLE, LV_PART_MAIN);
        logic_dev_status_led = status_led; // 保存状态LED指针
    }

    // 状态文本标签
    lv_obj_t *status_label = lv_label_create(status_container);
    if (status_label) {
        lv_label_set_text(status_label, "Disconnected");
        lv_obj_set_style_text_color(status_label, lv_color_hex(0xAAAAAA), LV_PART_MAIN);
        lv_obj_set_style_text_font(status_label, &myFont, LV_PART_MAIN);
        lv_obj_set_style_pad_left(status_label, 5, LV_PART_MAIN); // LED和文本间距
        logic_dev_status_label = status_label; // 保存状态文本标签指针
    }
    /******************** 引脚状态显示区域 - 优化间距 ********************/
    char *pin_names[16] = { "CH1", "CH2", "CH3", "CH4", "CH5", "CH6", "CH7", "CH8", "NC", "NC", "NC", "NC", "NC", "3v3", "5v0", "GND" };
    bool pin_status[16] = { true, true, true, true, true, true, true, true, false, false, false, false, false, true, true, true };
    uint32_t pin_color[16] = { 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00D2FF, 0x00D2FF, 0x00D2FF, 0x00D2FF, 0x00D2FF, 0xFF0000, 0xFF0000, 0x666666 };
    pin_item_t pins;
    pins.name = pin_names;
    pins.status = pin_status;
    pins.color = pin_color;

    func_pin_image(bottom_container, 2, 8, &pins);

    update_logic_dev_status(LOGIC_STATUS_CONNECTED);

    /***************启动逻辑分析仪任务***********************/
#if EABLE_LOGIC
    set_work_status(LOGIC_WORK);
    logic_analyzer_init();
#endif
    /***************启动逻辑分析仪任务 END***********************/

    return root;
}


// 更新设备状态函数
void update_logic_dev_status(logic_status_t status)
{
    lvgl_port_lock(0); // 进入LVGL临界区（确保线程安全）
    if (logic_dev_status_led) {
        switch (status) {
            case LOGIC_STATUS_DISCONNECTED:
                lv_led_set_color(logic_dev_status_led, lv_color_hex(0xFF5555)); // 红色
                lv_led_off(logic_dev_status_led);
                lv_label_set_text(logic_dev_status_label, "Disconnected");
                break;
            case LOGIC_STATUS_CONNECTED:
                lv_led_set_color(logic_dev_status_led, lv_color_hex(0x00FF00)); // 绿色
                lv_led_on(logic_dev_status_led);
                lv_label_set_text(logic_dev_status_label, "Connected");

                break;
            case LOGIC_STATUS_ACQUIRING:
                lv_led_set_color(logic_dev_status_led, lv_color_hex(0xFFFF00)); // 黄色
                lv_led_on(logic_dev_status_led);
                lv_label_set_text(logic_dev_status_label, "Acquiring");

                break;
            default:
                break;
        }
    }
    lvgl_port_unlock(); // 退出LVGL临界区
}
